﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using S.Common.ApiResult;
using S.Common.helper;
using S.Weaning.ApI.Application.Command;
using S.Weaning.Domain;
using S.Weaning.Domain.Dto;
using S.Weaning.Infrastructure.Interface;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using static S.Weaning.ApI.Application.Command.MaternalWeaningCommand;
using Newtonsoft.Json;
using S.Common.Enums.PregnancyTest;
using S.Weaning.ApI.Dto;
using System.Transactions;
using Azure;
using S.Common.EditReproductivePresenceStateHelper;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace S.Weaning.ApI.Application.CommandHandlers
{
    public class MaternalWeaningCommandHandler : IRequestHandler<AddMaternalMatingCommand, int>,IRequestHandler<UpdExamineCommand,bool>, IRequestHandler<DelMaternalCommand, bool>,IRequestHandler<UpdMaternalCommand, bool>
    {
        private readonly IWeaningRepository maternalWeaning;
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;
        private readonly IHttpContextAccessor httpContextAccessor;

        public MaternalWeaningCommandHandler(IWeaningRepository maternalWeaning, IMapper mapper,IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            this.maternalWeaning = maternalWeaning;
            this.mapper = mapper;
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
        }
        
        /// <summary>
        /// 断奶种母批量添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<int> Handle(AddMaternalMatingCommand request, CancellationToken cancellationToken)
        {
            string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer "))
            {
                authHeader = authHeader.Substring("Bearer ".Length).Trim();
            }
            string Gateway = configuration.GetValue<string>("Gateway");
            List<MaternalWeaningModel> maternalMatingModes = new List<MaternalWeaningModel>();

            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    foreach (var a in request.maternalWarnings)
                    {
                        // 断奶的添加

                        MaternalWeaningModel maternalweanimg = new MaternalWeaningModel()
                        {
                            UserId = request.UserId,
                            WeaningDate = request.WeaningDate,
                            DocumentNumber = request.DocumentNumber,
                            SerialNumber = request.SerialNumber,
                            Notes = request.Notes,
                            EITag = a.EITag,
                            EarTag = a.EarTag,
                            LactationDay = a.LactationDay,
                            TurnOutBuild = a.TurnOutBuild,
                            TurnOutHuts = a.TurnOutHuts,
                            TransferBuilding = a.TransferBuilding,
                            TransferField = a.TransferField,
                            TotalweaningWeightg = a.TotalweaningWeightg,
                            WeaningCount = a.WeaningCount,
                            SeedMotherWeightg = a.SeedMotherWeightg,
                            CreateBy = a.CreateBy,
                            CreateDate = DateTime.Now,
                        };

                        maternalMatingModes.Add(maternalweanimg);
                        //修改妊娠状态
                        EditReproductivePresenceState.UpdateReproductivePresenceState(a.EarTag, 1, 6, a.CreateDate, Gateway);
                        // 批量档案修改状态
                        parms parms = new parms()
                        {
                            earTag = new List<string> { a.EarTag },
                            wanderReproductiveState = 6,
                        };
                        HttpClientHelper.PutDataResponse(Gateway + "/achs/api/SheepFileModel/WanderStateEditPL", parms);
                        //修改种母状态
                        State state = new State()
                        {
                            earTag = new List<string> { a.EarTag },
                        };
                        HttpClientHelper.PostResponse(Gateway+ "/ParturitionSet/api/Parturition/UpdateParturition?earTag="+ a.EarTag +"" , "");

                        #region 反填并修改种母历史记录
                        request.editBreed.EarTag = a.EarTag;
                        //反填种母历史记录
                        var jsonString = HttpClientHelper.PostResponseKey(Gateway+ "/bhread/api/BreedingHistoryRead/GetBreedingHistoryById", request.editBreed);
                        //将获取到的种母历史记录序列化
                        var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);


                        //修改种母历史记录
                        response.WeaningDate = request.WeaningDate; //修改断奶日期
                        response.WeaningCount = a.WeaningCount; //修改断奶只数
                        response.TotalweaningWeightg = a.TotalweaningWeightg;//断奶总窝重
                        response.IsEditor = false;//不可在编辑
                                                  //修改种母历史记录
                        var breeding = HttpClientHelper.PutDataResponse(Gateway + "/bhset/api/BreedHistory/UpdateBreedingHistory", response);

                        #endregion
                        // 批量添加转舍记录
                        TransferRecords transfer = new TransferRecords()
                        {
                            EarTag = a.EarTag,
                            SurrenderDate = DateTime.Now,
                            RoundType = 5,
                            TurnOutBuild = Convert.ToInt32(a.TurnOutBuild),
                            TurnOutHuts = Convert.ToInt32(a.TurnOutHuts),
                            TurnOuBuildingManagementId = Convert.ToInt32(a.TurnOutBuild),
                            TurnOuColumnManagementId = Convert.ToInt32(a.TurnOutHuts),
                            ShiftToBuild = Convert.ToInt32(a.TransferBuilding),
                            ShiftToHuts = Convert.ToInt32(a.TransferField),
                            ShiftToBuildingManagementId = Convert.ToInt32(a.TransferBuilding),
                            ShiftToColumnManagementId = Convert.ToInt32(a.TransferField),
                            CreateBy = a.CreateBy,
                            CreateDate = DateTime.Now,
                        };
                        Transfer sheep = new Transfer();
                        sheep.sheep.Add(transfer);
                        HttpClientHelper.PostResponseKey(Gateway + "/transfer/api/TransFer/CreateSheepTransFers", sheep);
                    }
                

                    int rowsAffected =  maternalWeaning.AddMaternalWeaning(maternalMatingModes);

                    scope.Complete();

                    return rowsAffected;
                }
                catch (Exception ex)
                {
                    // 处理异常
                    scope.Dispose();
                    throw;
                }
            }
        }

        /// <summary>
        /// 进行审核
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(UpdExamineCommand request, CancellationToken cancellationToken)
        {
            var model = maternalWeaning.GetAll().FirstOrDefault(t => request.Ids.Contains(t.MaternalWeaningId.ToString()));
            model.ReviewedDate = DateTime.Now;
            model.ReviewedBy = "江建浩";
            return maternalWeaning.Update(model);
        }
        /// <summary>
        /// 种母断奶删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(DelMaternalCommand request, CancellationToken cancellationToken)
        {
            string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            string Gateway = configuration.GetValue<string>("Gateway");
            var items = maternalWeaning.GetAll();
             var matchingItems = items.Where(x => request.ids.Contains(x.MaternalWeaningId.ToString())).ToList();

            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    
                    foreach (var item in matchingItems)
                    {
                        maternalWeaning.Delete(item.MaternalWeaningId);
                        
                        // 批量档案修改状态
                        parms parms = new parms()
                        {
                            earTag = new List<string> { item.EarTag },
                            wanderReproductiveState = 5,
                        };
                        HttpClientHelper.PutDataResponse(Gateway + "/achs/api/SheepFileModel/WanderStateEditPL", parms);
                        //修改妊娠状态
                        EditReproductivePresenceState.UpdateReproductivePresenceState(item.EarTag, 1, 7, item.WeaningDate, Gateway);

                        // 修改种母状态
                        HttpClientHelper.PostResponse(Gateway + "/ParturitionSet/api/Parturition/UpdateParturition?earTag=" + item.EarTag + "", "");


                        // 定义并实例化 editBreeds 对象
                        editBreeds editBreed = new editBreeds();

                        // 设置 EarTag 属性的值
                        editBreed.EarTag = item.EarTag;

                        // 反填种母历史记录
                        var jsonString = HttpClientHelper.PostResponseKey(Gateway + "/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", editBreed);
                        // 将获取到的种母历史记录序列化
                        var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

                        // 修改种母历史记录
                        response.WeaningDate = null; // 修改断奶日期
                        response.WeaningCount = 0; // 修改断奶只数
                        response.TotalweaningWeightg = 0; // 断奶总窝重
                        response.IsEditor = true; // 不可再编辑
                                                  // 修改种母历史记录
                        var breeding = HttpClientHelper.PutDataResponse(Gateway + "/bhset/api/BreedHistory/UpdateBreedingHistory", response);


                        // 删除转舍记录
                        HttpClientHelper.DeleteResponse(Gateway + $"/transfer/api/TransFer/DeleteSheepTransFer?EarTag={item.EarTag}&CreateBy={item.CreateBy}");
                    
                    }

                    scope.Complete(); 

                    return true;
                }
                catch (Exception ex)
                {
                    // 处理异常情况
                    // ...
                    return false;
                }
            }

        }
        /// <summary>
        /// 修改种母断奶
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(UpdMaternalCommand request, CancellationToken cancellationToken)
        {
            string gateway = configuration.GetValue<string>("Gateway");
         var model=  maternalWeaning.GetAll().FirstOrDefault(t => t.MaternalWeaningId == request.MaternalWeaningId);

            model.MaternalWeaningId = request.MaternalWeaningId;
            model.UserId = request.UserId;
            model.WeaningDate = request.WeaningDate;
            model.Notes = request.Notes;
            model.EarTag = request.EarTag;
            model.LactationDay = request.LactationDay;
            model.TurnOutBuild = request.TurnOutBuild;
            model.TurnOutHuts = request.TurnOutHuts;
            model.TransferBuilding = request.TransferBuilding;
            model.TransferField = request.TransferField;
            model.TotalweaningWeightg = request.TotalweaningWeightg;
            model.WeaningCount = request.WeaningCount;
            model.SeedMotherWeightg = request.SeedMotherWeightg;
            model.UpdateBy = request.UpdateBy;
            model.UpdateDate = request.UpdateDate;

            //修改档案状态
            parms parms = new parms()
            {
                earTag = new List<string> { request.EarTag },
                wanderReproductiveState = 6,
            };
            HttpClientHelper.PutDataResponse($"{gateway}/achs/api/SheepFileModel/WanderStateEditPL", parms);
            // 定义并实例化 editBreeds 对象
            editBreeds editBreed = new editBreeds();

            // 设置 EarTag 属性的值
            editBreed.EarTag = request.EarTag;
            //反填种母信息
            var jsonString = HttpClientHelper.PostResponseKey($"{gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", editBreed);
            var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);
            response.WeaningDate =request.WeaningDate; // 修改断奶日期
            response.WeaningCount = request.WeaningCount; // 修改断奶只数
            response.TotalweaningWeightg = request.TotalweaningWeightg; // 断奶总窝重
            response.IsEditor = true; // 不可再编辑

            HttpClientHelper.PutDataResponse($"{gateway}/bhset/api/BreedHistory/UpdateBreedingHistory", response);
            var a= maternalWeaning.Update(model);

            return  a;

        }

        public editBreeds editBreed { get; set; }

        public class editBreeds 
        { 

            public string EarTag { get; set; }
        }


        public class BHparaList
        {
            public List<BHpara> breedingHistoryModelsList { get; set; }

            public BHparaList()
            {
                breedingHistoryModelsList = new List<BHpara>();
            }
        }
        //批量修改状态
        public class parms
        {
            public List<string> earTag { get; set; }

            public int wanderReproductiveState { get; set; }
        }

        //修改
        public class State
        {
            public List<string> earTag { get; set; }
        }
        //转舍添加
        public class Transfer
        {
            public List<TransferRecords> sheep { get; set; }

            public Transfer()
            {
                sheep = new List<TransferRecords>();
            }
        }
        public class TransferRecords
        {
            /// <summary>
            /// 转舍主键，自增标识列
            /// </summary>
            public int SheepRescissionId { get; set; }
            /// <summary>
            /// 可视耳标
            /// </summary>
            public string? EarTag { get; set; }
            /// <summary>
            /// 转舍日期
            /// </summary>
            public DateTime? SurrenderDate { get; set; }
            /// <summary>
            /// 转舍类型
            /// </summary>
            public int RoundType { get; set; }
            /// <summary>
            /// 转出栋舍
            /// </summary>
            public int TurnOutBuild { get; set; }

            /// <summary>
            /// 转出栏位
            /// </summary>
            public int TurnOutHuts { get; set; }
            /// <summary>
            /// 转出栋舍主键
            /// </summary>
            public int TurnOuBuildingManagementId { get; set; }
            /// <summary>
            /// 转出栏位主键
            /// </summary>
            public int TurnOuColumnManagementId { get; set; }
            /// <summary>
            /// 转入栋舍
            /// </summary>
            public int ShiftToBuild { get; set; }
            /// <summary>
            /// 转入栏位
            /// </summary>
            public int ShiftToHuts { get; set; }
            /// <summary>
            /// 转入栋舍主键
            /// </summary>
            public int ShiftToBuildingManagementId { get; set; }
            /// <summary>
            /// 转入栏位主键
            /// </summary>
            public int ShiftToColumnManagementId { get; set; }
            /// <summary>
            /// 品种
            /// </summary>
            public string? Variety { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            [Column(TypeName = "nvarchar(20)")]
            [MaxLength(20)]
            public string? CreateBy { get; set; }

            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime? CreateDate { get; set; }

            /// <summary>
            /// 修改人
            /// </summary>
            [Column(TypeName = "nvarchar(20)")]
            [MaxLength(20)]
            public string? UpdateBy { get; set; }

            /// <summary>
            /// 修改时间
            /// </summary>
            public DateTime? UpdateDate { get; set; }
            /// <summary>
            /// 是否删除
            /// </summary>
            public bool IsDel { get; set; }
            /// <summary>
            /// 单据号
            /// </summary>
            public long DocumentNumbe { get; set; }
            /// <summary>
            /// 羊只类型
            /// </summary>
            public string? Type { get; set; }
        }
        //添加种母历史记录
        public class BHpara
        {
            public int BDHRId { get; set; }
            /// <summary>
            /// 种母电子耳标
            /// </summary>
            [Column(TypeName = "nvarchar(50)")]
            [MaxLength(50)]
            public string? earTag { get; set; }
            /// <summary>
            /// 配种日期
            /// </summary>
            public DateTime? breedingDate { get; set; }
            /// <summary>
            /// 种公电子耳号
            /// </summary>
            [Column(TypeName = "nvarchar(50)")]
            [MaxLength(50)]
            public string? breedingRam { get; set; }
            /// <summary>
            /// 妊检日期
            /// </summary>
            public DateTime? pregnancyDate { get; set; }
            /// <summary>
            /// 妊检结果
            /// </summary>
            public int pregnancytestResult { get; set; }
            /// <summary>
            /// 分娩日期
            /// </summary>
            public DateTime? deliveryDate { get; set; }
            /// <summary>
            /// 健羔数
            /// </summary>
            public int healthyNumber { get; set; }
            /// <summary>
            /// 健羔总重
            /// </summary>
            public decimal totalWeightOfHealthyLambs { get; set; }
            /// <summary>
            /// 弱羔数
            /// </summary>
            public int lambNumber { get; set; }
            /// <summary>
            /// 畸形数
            /// </summary>
            public int deformityNumber { get; set; }
            /// <summary>
            /// 死胎数
            /// </summary>
            public int stillbirthsNumber { get; set; }
            /// <summary>
            /// 木乃伊数
            /// </summary>
            public int mummyNumber { get; set; }
            /// <summary>
            /// 畸胎数
            /// </summary>
            public int freaksNumber { get; set; }
            /// <summary>
            /// 当前胎次
            /// </summary>
            public int currentPregnancy { get; set; }
            /// <summary>
            /// 断奶日期
            /// </summary>
            public DateTime? weaningDate { get; set; }
            /// <summary>
            /// 断奶只数
            /// </summary>
            public int weaningCount { get; set; }
            /// <summary>
            /// 断奶窝重
            /// </summary>
            public decimal totalweaningWeightg { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            public string? createBy { get; set; }
            /// <summary>
            /// 创建日期
            /// </summary>
            public DateTime? createDate { get; set; }
            /// <summary>
            /// 修改人
            /// </summary>
            public string? updateBy { get; set; }
            /// <summary>
            /// 修改日期
            /// </summary>
            public DateTime? updateDate { get; set; }
            /// <summary>
            /// 逻辑删除标志
            /// </summary>
            public bool isDel { get; set; }
            /// <summary>
            /// 是否可编辑（默认可编辑）
            /// </summary>
            public bool isEditor { get; set; } = true;
            /// <summary>
            /// 种母发情类型
            /// </summary>
            public int? estrusTypeId { get; set; }

            /// <summary>
            /// 种公品种
            /// </summary>
            public string? seedVariety { get; set; }
        }
    }
}
